package com.sysd.server.handler;

import com.sysd.bean.ErrorMessage;
import com.sysd.entity.LoginUser;
import com.sysd.exception.ServiceException;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static com.sysd.server.container.AttrContainer.channelUserIdAttr;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @description: 另一种鉴权方式，暂时没调试过这个是再协议升级前就要完成调试
 * @author: bsh
 * @date: 2025/6/13 09:45
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ChannelHandler.Sharable
public class Auth1Handler extends ChannelInboundHandlerAdapter {
    /**
     * handle request
     *
     * @param ctx    上下文
     * @param object 消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) {
        if (object instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) object;
            String token = getHeader(request, "token");
            String timestamp = getHeader(request, "timestamp");
            //去其他地方请求获取的信息
            LoginUser u = Optional.ofNullable(token).map(i -> new LoginUser(1, "", "", "")).orElse(null);
            if (null == u) {
                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED,
                        Unpooled.copiedBuffer("Token不存在", CharsetUtil.UTF_8));
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
                return;
            }
            ctx.channel().attr(channelUserIdAttr).set(u.getUserId());
            ctx.fireUserEventTriggered(u);
        }
        //传递出去
        try {
            super.channelRead(ctx, object);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * netty exception
     *
     * @param ctx   上下文
     * @param cause 异常原因
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("服务异常{}", cause.getMessage());
        ctx.writeAndFlush(ErrorMessage.defaultError("程序异常,连接关闭!")).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * get param
     *
     * @param req  请求信息
     * @param name 参数
     * @return res
     */
    private static String getRequestParameter(FullHttpRequest req, String name) {
        QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
        Map<String, List<String>> parameters = decoder.parameters();
        Set<Map.Entry<String, List<String>>> entrySet = parameters.entrySet();
        for (Map.Entry<String, List<String>> entry : entrySet) {
            if (entry.getKey().equalsIgnoreCase(name)) {
                return entry.getValue().get(0);
            }
        }
        return null;
    }

    /**
     * 获取请求头信息
     *
     * @param request request
     * @param name    需要找的参数
     * @return res
     */
    private static String getHeader(FullHttpRequest request, String name) {
        return request.headers().get(name);
    }
}
